const puppeteer = require("puppeteer");
const moment = require("moment");
// 启动计时器

const sleep = seconds =>
  new Promise(resolve => {
    console.log(
      `--------------------------------^~~~^------------ sleep ${seconds} mseconds!`
    );
    setTimeout(resolve, seconds);
  });

(async function() {
  console.time("testForEach");
  const browser = await puppeteer.launch({
    headless: false
  });
  const page = await browser.newPage();
  await page.setViewport({
    width: 1280,
    height: 1024
  });
  await page.goto("http://epprd.shccmg.com:58000/irj/portal", {
    waitUntil: "load"
  });
  await page.waitFor(500);

  await page.type("#logonuidfield", "09106017", {
    delay: 2
  });
  await page.type("#logonpassfield", "chengzhe", {
    delay: 2
  });

  await page.click("input[name=uidPasswordLogon]");
  await sleep(3000);

  let mainFrame = await page.mainFrame();
  await mainFrame.waitForSelector("#tabIndex1");
  await mainFrame.click("#tabIndex1");

  await sleep(3000);
  let frames = await page.frames();
  if (!frames || frames.length < 2) {
    return new Error("未获取到计划查询报表frame！");
  }
  let planFrame = frames[frames.length - 1];
  await planFrame.waitForSelector("#WD2B-btn");
  await planFrame.click("#WD2B-btn");
  await planFrame.waitFor(500);
  await planFrame.click("#WD2F");
  await planFrame.waitFor(500);
  await planFrame.click("#WDA1-btn");
  await planFrame.waitFor(1000);
  let day = "2018-04-04";
  let Account = moment().format("YYYY-MM");
  let firstDay = moment().format("YYYY-MM-01");
  let monFirstDay = moment(day).format("x");
  await planFrame.click(`div[date='${monFirstDay}']`);
  await sleep(500);
  await planFrame.click("#WDBF span.urBtnRow:nth-child(1)");
  await sleep(3000);
  //
  // 获取所有数据条数
  let totalCount = await planFrame.$eval("#WDC4", el => {
    return el.textContent.match(/\d+/)[0] || 0;
  });
  console.log(`the totalCount:${totalCount}`);
  // 如果大于10，先获取前10条，如果小于10条则为全部数据
  let top = [];
  top = await planFrame.evaluate(() => {
    let trs = [...document.querySelectorAll("#WDE4-contentTBody tr[rr]")];
    return trs.map(el => {
      let inputs = [
        ...el.querySelectorAll("#WDE4-contentTBody tr[rr] input[id]")
      ];
      if (inputs.length > 0) {
        let PPlanID = inputs[0].value || "";
        let BID = inputs[1].value || "";
        let WZID = inputs[3].value || "";
        let LBID = inputs[4].value || "";
        let WZName = inputs[5].value || "";
        let IsK = inputs[6].value || "";
        let PlanNum = parseFloat(inputs[7].value || "0").toFixed(3);
        let Unit = inputs[8].value || "";
        let PriceUnit = parseInt(inputs[9].value || "1");
        let PlanPrice = parseFloat(inputs[10].value || "").toFixed(2);
        let PlanMoney = parseFloat(inputs[11].value || "").toFixed(2);
        let Prgf = inputs[13].value || "";
        let PlanArrDate = inputs[14].value || "";
        let Prg = inputs[15].value || "";
        let Dept = inputs[16].value || "";
        let CGType = inputs[17].value || "";
        let NextID = el.querySelector("#WDE4-contentTBody tr[rr] a")
          .textContent;
        let NextItem = inputs[18].value.trim() || "";
        let IsPress = inputs[19].value || "";
        let IsTrade = inputs[20].value || "";
        let PPLanCdate = inputs[21].value || "";
        let YPrID = inputs[24].value || "";
        let YPrItem = inputs[25].value || "";
        let BIDName = inputs[26].value || "";
        let BXJType = inputs[28].value || "";
        let BZBType = inputs[29].value || "";
        let BOrderType = inputs[30].value || "";
        let GYSID = inputs[34].value || "";
        let GYName = inputs[35].value || "";
        let IsJC = inputs[36].value || "";
        let PlanID = inputs[42].value || "";
        return {
          id: el.getAttribute("rr") || 0,
          PPlanID,
          BID,
          WZID,
          LBID,
          WZName,
          IsK,
          PlanNum,
          Unit,
          PriceUnit,
          PlanPrice,
          PlanMoney,
          Prgf,
          PlanArrDate,
          Prg,
          Dept,
          CGType,
          NextID,
          NextItem,
          IsPress,
          IsTrade,
          PPLanCdate,
          YPrID,
          YPrItem,
          BIDName,
          BXJType,
          BZBType,
          BOrderType,
          GYSID,
          GYName,
          IsJC,
          PlanID
        };
      }
    });
  });
  if (totalCount > 10) {
    for (let i = 11; i <= totalCount; i++) {
      await planFrame.click("#WDE4-scrollV-Nxt");
      // await planFrame.waitFor(100)
      // 每点击一下，获取当前表格最后一条数据
      let lastTr = `tr[rr="${i.toString()}"]`;
      await planFrame.waitForSelector(lastTr);
      let thisItem = await planFrame.$eval(lastTr, el => {
        let inputs = [...el.querySelectorAll("input[id]")];
        if (inputs.length > 0) {
          let PPlanID = inputs[0].value || "";
          let BID = inputs[1].value || "";
          let WZID = inputs[3].value || "";
          let LBID = inputs[4].value || "";
          let WZName = inputs[5].value || "";
          let IsK = inputs[6].value || "";
          let PlanNum = parseFloat(inputs[7].value || "0").toFixed(3);
          let Unit = inputs[8].value || "";
          let PriceUnit = parseInt(inputs[9].value || "1");
          let PlanPrice = parseFloat(inputs[10].value || "").toFixed(2);
          let PlanMoney = parseFloat(inputs[11].value || "").toFixed(2);
          let Prgf = inputs[13].value || "";
          let PlanArrDate = inputs[14].value || "";
          let Prg = inputs[15].value || "";
          let Dept = inputs[16].value || "";
          let CGType = inputs[17].value || "";
          let NextID = el.querySelector("#WDE4-contentTBody tr[rr] a")
            .textContent;
          let NextItem = inputs[18].value.trim() || "";
          let IsPress = inputs[19].value || "";
          let IsTrade = inputs[20].value || "";
          let PPLanCdate = inputs[21].value || "";
          let YPrID = inputs[24].value || "";
          let YPrItem = inputs[25].value || "";
          let BIDName = inputs[26].value || "";
          let BXJType = inputs[28].value || "";
          let BZBType = inputs[29].value || "";
          let BOrderType = inputs[30].value || "";
          let GYSID = inputs[34].value || "";
          let GYName = inputs[35].value || "";
          let IsJC = inputs[36].value || "";
          let PlanID = inputs[42].value || "";
          return {
            id: el.getAttribute("rr") || 0,
            PPlanID,
            BID,
            WZID,
            LBID,
            WZName,
            IsK,
            PlanNum,
            Unit,
            PriceUnit,
            PlanPrice,
            PlanMoney,
            Prgf,
            PlanArrDate,
            Prg,
            Dept,
            CGType,
            NextID,
            NextItem,
            IsPress,
            IsTrade,
            PPLanCdate,
            YPrID,
            YPrItem,
            BIDName,
            BXJType,
            BZBType,
            BOrderType,
            GYSID,
            GYName,
            IsJC,
            PlanID
          };
        }
      });
      top.push(thisItem);
      console.log(`this loop At:${i}\r`, thisItem);
    }
  }

  console.log(`this is the top  `);
  console.log(top);

  await sleep(5000);
  await browser.close();
  console.timeEnd("testForEach");
})();
// 启动计时器
